package com.it.xyx.code.asyncDemo;

import jdk.nashorn.internal.runtime.logging.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Logger
@RestController
public class AsyncController {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(AsyncController.class);
    @Resource
    private AsyncService asyncService;

    //单个调度
    @GetMapping("/execute")
    public void executeAll() throws Exception {
        // 记录开始时间
        long start = System.currentTimeMillis();

        // 并行调用多个方法
        CompletableFuture<String> futureA = asyncService.methodA("a");
        CompletableFuture<String> futureB = asyncService.methodA("b");

        // 等待所有任务完成（阻塞）
        CompletableFuture.allOf(futureA, futureB).join();

        // 获取结果
        String resultA = futureA.get();
        String resultB = futureB.get();

        // 后续操作
        String finalResult = resultA + " | " + resultB;
        long duration = System.currentTimeMillis() - start;
        log.info(duration + "ms");
        log.info(finalResult);

    }

    //批量调度
    @GetMapping("/batch-process")
    public void processBatch() {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        List<String> items = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            items.add(String.valueOf(i));
        }
        // 创建所有异步任务
        List<CompletableFuture<String>> futures = items.stream()
                .map(item -> asyncService.methodB(item))
                .collect(Collectors.toList());

        // 合并所有 Future 并等待完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
        );

        // 获取结果（带异常处理）
        CompletableFuture<List<String>> resultsFuture = allFutures.thenApply(v ->
                futures.stream()
                        .map(future -> {
                            try {
                                return future.get();
                            } catch (Exception e) {
                                return "ERROR: " + e.getMessage();
                            }
                        })
                        .collect(Collectors.toList())
        );

        // 阻塞获取结果
        List<String> results = resultsFuture.join();
        log.info("阻塞结果返回: {}", results);
        // 后续操作
        log.info("总耗时: {}ms", System.currentTimeMillis() - startTime);
    }

    @Resource
    BatchInsertService batchInsertService;

    @PostMapping("/import")
    public void importData() {
        List<UserData> dataList = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            UserData data = new UserData();
            data.setName("name" + i);
            data.setContent(String.valueOf(i));
            dataList.add(data);


        }
        // 数据分片（每个分片500条）
        List<List<UserData>> partitions = batchInsertService.partition(dataList, 500);
        List<CompletableFuture<Integer>> futures = new ArrayList<>();

        // 提交并行任务
        partitions.forEach(partition ->
                futures.add(batchInsertService.asyncBatchInsert(partition))
        );

        // 合并结果
        int total = futures.stream()
                .map(CompletableFuture::join)
                .reduce(Integer::sum)
                .orElse(0);

        log.info(total + "条");
    }

}




